package com.program.facesigninsystem.controller;

import cn.yueshutong.springbootstartercurrentlimiting.annotation.CurrentLimiter;
import com.program.facesigninsystem.entity.Classes;
import com.program.facesigninsystem.entity.ResponseModel;
import com.program.facesigninsystem.entity.UserClass;
import com.program.facesigninsystem.service.IClassesService;
import com.program.facesigninsystem.service.IUserClassService;
import com.program.facesigninsystem.util.FileUtil;
import com.program.facesigninsystem.util.GetInfoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author 盛旭雯
 */
@CrossOrigin
@RestController
@RequestMapping(value = "/class")
public class ClassesController {
    private static Logger log = Logger.getLogger(ClassesController.class.toString());
    @Autowired
    public IClassesService iClassesService;

    /****
     * 创建名单
     * @param tid 教师id
     * @param name
     * @param t_count
     * @return responseModel
     */
    @RequestMapping(value = "/createClass",method = RequestMethod.GET)
    public ResponseModel createNewClass(@RequestParam("tid")String tid,@RequestParam("name")String name,@RequestParam("t_count")int t_count){
        String cid = GetInfoUtil.getId();
        int r_count=0;
        ResponseModel responseModel;
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String currentTime = simpleDateFormat.format(System.currentTimeMillis());
            iClassesService.insertClasses(cid,name,r_count,t_count,tid,currentTime);
            responseModel = new ResponseModel(200,"新建成功");
        }catch (Exception e){
            responseModel = new ResponseModel(199,"新建失败");
        }
        return responseModel;
    }

    @Autowired
    public IUserClassService iUserClassService;

    /***
     * 加入名单
     *
     * @param uid
     * @param cid
     * @return
     */
    @RequestMapping(value = "/joinClass",method = RequestMethod.GET)
    @CurrentLimiter(QPS=5)
    public synchronized ResponseModel joinClass(@RequestParam("uid")String uid,@RequestParam("cid")String cid){
        Classes classes=iClassesService.selectClass(cid);
        ResponseModel responseModel;
        if(classes == null) {
            return new ResponseModel(199,"名单不存在");
        }
        if(classes.getR_count()<classes.getT_count()){
            UserClass userClass =iUserClassService.selectUserClass(uid,cid);
            if(userClass==null){
                iUserClassService.insertUserClass(uid,cid);
                iClassesService.updateAddCount(cid);
                responseModel = new ResponseModel(200,"加入成功");
            }else{
                responseModel = new ResponseModel(199,"您已加入该名单");
            }
        }else{
            responseModel = new ResponseModel(199,"该名单已满员");
        }
        return responseModel;
    }

    /***
     * 按发起者id查找名单列表
     * @param tid
     * @return
     */
    @RequestMapping(value = "/findClassListByTid",method = RequestMethod.GET)
    public  ResponseModel findClassListByTid(@RequestParam("tid")String tid){
        try {
            List<Classes> classesList = iClassesService.selectClassListByTid(tid);
            return new ResponseModel(200,"查询成功",classesList);
        }catch (Exception e) {
            return new ResponseModel(199,"查询失败");
        }
    }

    /***
     * 按名单班级更新名单人数限制
     * @param cid
     * @param t_count
     * @return
     */
    @RequestMapping(value = "/updateClassTCount",method = RequestMethod.GET)
    public  ResponseModel updateClassTCount(@RequestParam("cid")String cid,@RequestParam("t_count")int t_count){
        ResponseModel responseModel;
        try {
            iClassesService.updateClassTCount(cid,t_count);
            responseModel = new ResponseModel(200,"更新成功");
        }catch (Exception e){
            responseModel = new ResponseModel(199,"更新失败");
        }
        return responseModel;
    }

    /****
     * 删除名单
     * @param cid
     * @return
     */
    @RequestMapping(value = "/deleteClass",method = RequestMethod.GET)
    public  ResponseModel deleteClass(@RequestParam("cid")String cid){
        ResponseModel responseModel;
        try{
            iClassesService.deleteClass(cid);
            responseModel = new ResponseModel(200,"删除成功");
        }catch (Exception e){
            responseModel = new ResponseModel(199,"删除失败");
        }
        return responseModel;
    }

    /***
     * 删除名单成员
     * @param uid
     * @param cid
     * @return
     */
    @Transactional
    @RequestMapping(value = "/deleteUserInClass",method = RequestMethod.GET)
    public  ResponseModel deleteUserInClass(@RequestParam("uid")String uid,@RequestParam("cid")String cid){
        ResponseModel responseModel;
        try{
            iUserClassService.deleteUserClass(uid,cid);
            iClassesService.updateSubCount(cid);
            responseModel = new ResponseModel(200,"删除成功");
        }catch (Exception e){
            responseModel = new ResponseModel(199,"删除失败");
        }
        return responseModel;
    }

    /***
     * 查找名单成员列表
     * @param cid
     * @return
     */
    @RequestMapping(value = "/selectUserList",method = RequestMethod.GET)
    public  ResponseModel selectUserList(@RequestParam("cid")String cid){
        Classes classes=iClassesService.selectClass(cid);
        ResponseModel responseModel;
        if(classes == null) {
            return new ResponseModel(199,"名单不存在");
        }
        if(classes.getR_count()!=0){
            try{
                List<Map<String,Object>> userList=iUserClassService.selectUserList(cid);
                responseModel = new ResponseModel(200,"获取成功",userList);
            }catch (Exception e){
                responseModel = new ResponseModel(199,"获取失败");
            }
        }else{
            responseModel = new ResponseModel(199,"暂无成员");
        }
        return responseModel;
    }

    @RequestMapping(value = "/uploadClassList",method = RequestMethod.POST)
    public  ResponseModel uploadClassList(@RequestParam("uid")String uid, @RequestParam("list")MultipartFile list,@RequestParam(value = "fileName",required = false)String name){
        String fileType1 = "application/vnd.ms-excel";
        String fileType2= "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        if(!fileType1.equals(list.getContentType())&&!fileType2.equals(list.getContentType())) {
            System.out.println(list.getContentType());
            return new ResponseModel(116,"上传失败，只支持xls/xlsx文件");
        }
        String filePath = "C:/uploadFiles/" +"signInList"+"/"+uid+"/";
        String createTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String fileName = name  == null?list.getOriginalFilename():name;
        File file= FileUtil.loadFile(filePath,createTime,list,fileName);
        if (file==null||!file.exists()){
            return new ResponseModel(116,"上传失败");
        }
        String url = "https://www.xqzjgsu.xyz/upload/"+"signInList"+"/"+uid+"/"+ createTime + fileName;
        try {
            iClassesService.insertSignInList(uid,filePath+createTime+fileName,fileName,url);
            return new ResponseModel(200,"上传成功");
        }catch (Exception e){
            if(!file.delete()){
                System.out.println("文件删除失败");
            }
            return new ResponseModel(119,"数据库存入失败");
        }
    }

    @RequestMapping(value = "/classListHistory",method = RequestMethod.GET)
    public  ResponseModel classListHistory(@RequestParam("uid")String uid){
        try {
            return new ResponseModel(200,"获取成功",iClassesService.selectSignInListByUid(uid));
        }catch (Exception e){
            log.log(Level.SEVERE,"Error parsing date",e);
            return new ResponseModel(119,"获取失败");
        }
    }

    @RequestMapping(value = "/deleteListFile",method = RequestMethod.GET)
    public  ResponseModel deleteListFile(@RequestParam("uid")String uid,@RequestParam("id")int id,@RequestParam("filePath")String filePath){
        try {
            iClassesService.deleteSignInList(uid, id);
            File file = new File(filePath);
            if(!file.delete()){
                return new ResponseModel(113,"删除失败");
            }
            return new ResponseModel(200,"删除成功");
        }catch (Exception e){
            log.log(Level.SEVERE,"Error parsing date",e);
            return new ResponseModel(113,"删除失败");
        }
    }

    @RequestMapping(value = "/selectClassNum",method = RequestMethod.GET)
    public ResponseModel selectClassNum(@RequestParam("cid")String cid){
        Classes classes = iClassesService.selectClass(cid);
        if(classes == null){
            return new ResponseModel(200,"无名单");
        }else{
            return new ResponseModel(200,"获取成功",classes.getT_count());
        }
    }
}
